package com.zondy.dizhi.server.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.baidu.mapapi.http.HttpClient;


/**
 * 从服务器下载对应的应用apk到手机相应位置
 * @author ldf
 *
 */
public class LoadApkService {
	public static final int MESSAGEFROMFLAG_DOWNLOAD_APK = 0001;
	private String filePath;
	private File file;
	private boolean needProcess = true;
	private int loadRate = 10;
	private String strUrl;
	private Handler handler;
	
	/**
	 * 构造函数
	 * @param context            上下文
	 * @param strUrl             服务器url地址
	 * @param filePath           手机存储路径
	 * @param handler            UI更新handler
	 */
	public LoadApkService(Context context, String strUrl, String filePath, Handler handler){

		this.filePath = filePath;
		this.strUrl = strUrl;
		this.handler = handler;
	}
	
	/**
	 * 网络请求服务下载对应的应用apk
	 * @return
	 */
	public boolean call() {

		InputStream conIs = null;
		OutputStream fileOs = null;
		try {
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
			HttpConnectionParams.setSoTimeout(httpParams, 60000);
			DefaultHttpClient client = new DefaultHttpClient(httpParams);
			HttpGet httpGet = new HttpGet(strUrl); 
			HttpResponse response = client.execute(httpGet); 
			conIs = response.getEntity().getContent();
			double fileSize = response.getEntity().getContentLength();
			
			file = new File(filePath);
			if(file.exists()){
				file.delete();	
			}	
			file.createNewFile();
			
			fileOs = new FileOutputStream(file);
			byte[] data = new byte[loadRate * 1024];
            int len = -1, hasRead = 0, curPos = 0;
            while((len = conIs.read(data)) != -1 && curPos <= 100) {
            	fileOs.write(data, 0, len);
            	hasRead += len;
        		curPos = (int)(hasRead / fileSize * 100);
            	if(needProcess){//需要进度条显示
            		Message message = handler.obtainMessage();
            		message.what = 1;
            		message.arg1 = curPos;
            		message.sendToTarget();            		
            	}
            }      
            fileOs.flush();
			
		} catch(IOException ioExp) {
			ioExp.printStackTrace();
			
		} catch (Exception e) {
			
		} finally{
            try {
				fileOs.close();	            
				conIs.close();					
			} catch (IOException e) {
			} catch (Exception e2) {
			}
		}
		return true;
	}
}
